package src.DAO;

import src.jdbc.PostgreSQL;
import src.Entities.Region;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
/**
 *
 * @author Rodrigo
 */
public class RegionDAO {

    public String deleteRegion(int regionID){
        try {
            String sql = "DELETE FROM region WHERE region_id = ?;";
            PreparedStatement delete = PostgreSQL.getConnection().prepareStatement(sql);
            delete.setInt(1, regionID);
            return String.valueOf(delete.execute());
        } catch (Exception e) {
            return e.toString();
        }
    }

    public String insertRegion(Region region) {
        try {
            String sql = "INSERT " +
                    "       INTO region(region_id, pais_id, nombre)" +
                    "     VALUES (NEXTVAL('region_seq'), ?, ?)";
            PreparedStatement insert = PostgreSQL.getConnection().prepareStatement(sql);
            insert.setInt(1, region.getPaisId());
            insert.setString(2, region.getNombre());
            return String.valueOf(insert.execute());
        } catch (Exception e) {
            return e.toString();
        }
    }

    public ArrayList selectRegion(String sql) {
        ArrayList results = new ArrayList();
        try {
            Connection con = PostgreSQL.getConnection();
            Statement select = con.createStatement();
            ResultSet query = select.executeQuery(sql);
            while (query.next()) {
                Region region = new Region(query.getInt("region_id"),
                        query.getInt("pais_id"), query.getString("nombre"));
                results.add(region);
            }
        } catch (Exception e) {
            System.out.println(e);
        }
        return results;
    }

    public String updateRegion(Region region) {
        try {
            String sql = "UPDATE region" +
                    "        SET pais_id = ?, nombre = ?" +
                    "      WHERE region_id = ?";
            PreparedStatement update = PostgreSQL.getConnection().prepareStatement(sql);
            update.setInt(1, region.getPaisId());
            update.setString(2, region.getNombre());
            update.setInt(3, region.getRegionId());
            return String.valueOf(update.execute());
        } catch (Exception e) {
            return e.toString();
        }
    }
}
